<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-bounce.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"zhiruozzy.cn","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":"truw","sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="文件操作的相关知识点总结和程设中的演示程序的详解">
<meta property="og:type" content="article">
<meta property="og:title" content="文件操作">
<meta property="og:url" content="http://zhiruozzy.cn/2022/04/01/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/index.html">
<meta property="og:site_name" content="芷若">
<meta property="og:description" content="文件操作的相关知识点总结和程设中的演示程序的详解">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://zhiruozzy.cn/img/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/image-20220401230356231.png">
<meta property="og:image" content="http://zhiruozzy.cn/img/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/image-20220401230628109.png">
<meta property="og:image" content="http://zhiruozzy.cn/img/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/image-20220402111008546.png">
<meta property="article:published_time" content="2022-04-01T02:26:56.000Z">
<meta property="article:modified_time" content="2022-04-02T03:12:17.418Z">
<meta property="article:author" content="芷若">
<meta property="article:tag" content="C语言">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://zhiruozzy.cn/img/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/image-20220401230356231.png">

<link rel="canonical" href="http://zhiruozzy.cn/2022/04/01/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>文件操作 | 芷若</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --><link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">芷若</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-主页">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>主页</a>

  </li>
        <li class="menu-item menu-item-关于">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-标签">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-目录">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>目录</a>

  </li>
        <li class="menu-item menu-item-归档">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container"></div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="algolia-results">
  <div id="algolia-stats"></div>
  <div id="algolia-hits"></div>
  <div id="algolia-pagination" class="algolia-pagination"></div>
</div>

      
    </div>
  </div>

</div>
    </header>

    
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/zhiruozzy" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://zhiruozzy.cn/2022/04/01/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/touxiang.jpg">
      <meta itemprop="name" content="芷若">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="芷若">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          文件操作
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-04-01 10:26:56" itemprop="dateCreated datePublished" datetime="2022-04-01T10:26:56+08:00">2022-04-01</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-04-02 11:12:17" itemprop="dateModified" datetime="2022-04-02T11:12:17+08:00">2022-04-02</time>
              </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>5.1k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>5 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>文件操作的相关知识点总结和程设中的演示程序的详解</p>
<span id="more"></span>

<h3 id="文件分类"><a href="#文件分类" class="headerlink" title="文件分类"></a>文件分类</h3><p>文件分为文本文件(.txt)和二进制文件</p>
<p>文本文件：保存的时候，每一个字符对应一个字节</p>
<p>二进制文件：二进制编码保存的文件</p>
<h3 id="设备文件"><a href="#设备文件" class="headerlink" title="设备文件"></a>设备文件</h3><p>当启动一个程序的时候，系统会打开3个设备文件</p>
<p>stdin:标准输入文件(鼠标，键盘)，默认情况下，标准输入设备是硬盘</p>
<p>stdout:标准输出文件（显示器），默认情况下，标准输出设备是显示器</p>
<p>stderr:标准错误文件，一般为显示器</p>
<h3 id="文件的重定向"><a href="#文件的重定向" class="headerlink" title="文件的重定向"></a>文件的重定向</h3><p>重定向符号：</p>
<p>“&lt;” 输入重定向 </p>
<p>“&gt;”输出重定向</p>
<p>以下面这个程序为例：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">()</span></span><br><span class="line">&#123;</span><br><span class="line">   <span class="type">int</span> i;</span><br><span class="line">   <span class="type">int</span> a[<span class="number">5</span>];  </span><br><span class="line">   <span class="built_in">printf</span>(<span class="string">&quot;input 5 numbers:\n&quot;</span>);   </span><br><span class="line">   <span class="keyword">for</span>(i=<span class="number">0</span>;i&lt;=<span class="number">4</span>;i++)</span><br><span class="line">      <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>,&amp;a[i]);</span><br><span class="line"></span><br><span class="line">   <span class="built_in">printf</span>(<span class="string">&quot;the 5 numbers are:\n&quot;</span>);     </span><br><span class="line">   <span class="keyword">for</span>(i=<span class="number">0</span>;i&lt;=<span class="number">4</span>;i++)</span><br><span class="line">      <span class="built_in">printf</span>(<span class="string">&quot;%d,&quot;</span>,a[i]);    </span><br><span class="line">        </span><br><span class="line">   <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>这个程序就是只有标准输入输出，即我可以直接在编译器中运行，得到的结果是这样的：</p>
<p><img src="/../img/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/image-20220401230356231.png" alt="image-20220401230356231"></p>
<p>重定向：将标准输入换成文件输入输出，即输入流改为data1.txt这个文件，将结果输出到data2.txt中。</p>
<p>方法：在放程序的这个文件夹中新建data1.txt，输入1，2，3，4，5并保存。在在文件资源管理器中找到本程序的exe文件所在的位置，在cmd中输入可执行程序的名字和重定向的位置，就可以在新建的data2.txt中得到输出结果</p>
<p><img src="/../img/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/image-20220401230628109.png" alt="image-20220401230628109"></p>
<h3 id="文件访问方式"><a href="#文件访问方式" class="headerlink" title="文件访问方式"></a>文件访问方式</h3><table>
<thead>
<tr>
<th align="left">模式</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">r</td>
<td align="left">只读的方式打开。不创建文件，如果文件不存在会报错</td>
</tr>
<tr>
<td align="left">w</td>
<td align="left">只写的方式打开。如果文件不存在，则会创建一个新文件。如果文件存在，则会先清空文件中原来的内容，在重新写入。</td>
</tr>
<tr>
<td align="left">a</td>
<td align="left">追加的方式打开。如果文件不存在，则会创建一个新文件。如果文件存在，会在已有的文件内容中追加内容。</td>
</tr>
<tr>
<td align="left">r+</td>
<td align="left">可读可写的方式打开，不创建新文件</td>
</tr>
<tr>
<td align="left">w+</td>
<td align="left">可读可写的方式打开。如果文件已存在，则文件会被截断为零长度，如果文件不存在，则会创建一个新文件。</td>
</tr>
<tr>
<td align="left">a+</td>
<td align="left">允许读写文件。如果文件不存在，则会创建一个新文件。读取会从文件的开头开始，写入则只能是追加模式。</td>
</tr>
</tbody></table>
<p>如果处理的是二进制文件，则需要使用下面的访问方式：</p>
<p><code>&quot;rb&quot;, &quot;wb&quot;, &quot;ab&quot;, &quot;rb+&quot;, &quot;r+b&quot;, &quot;wb+&quot;, &quot;w+b&quot;, &quot;ab+&quot;, &quot;a+b&quot;</code></p>
<p>常用的就是“r”和“w”，r:不创建也不清空，w:会创建也会清空</p>
<h3 id="打开文件：fopen"><a href="#打开文件：fopen" class="headerlink" title="打开文件：fopen"></a>打开文件：fopen</h3><p>语法：<code>FILE *fopen(const char *文件名,&quot;文件访问模式&quot;)</code></p>
<p>返回值：成功：指向该文件的文件流的指针（即FILE结构体的地址）</p>
<p>​              失败：NULL</p>
<p>例子：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">FILE*fp=fopen(<span class="string">&quot;./a.txt&quot;</span>,<span class="string">&quot;r&quot;</span>);</span><br><span class="line"><span class="keyword">if</span>(fp==<span class="literal">NULL</span>)</span><br><span class="line">&#123;</span><br><span class="line">  perror(<span class="string">&quot;Error&quot;</span>);</span><br><span class="line">  <span class="keyword">return</span> ;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>perror() 函数：把错误消息输出到标准错误 stderr。</p>
<p>语法：<code>void perror(const char *str)</code></p>
<p>格式：输出字符串 <strong>str</strong>，后跟一个冒号，然后是一个空格,然后是错误信息</p>
<p>如果此文件夹下没有a.txt的文件，则会输出<code>Error: No such file or directory</code></p>
<h3 id="关闭文件：fclose"><a href="#关闭文件：fclose" class="headerlink" title="关闭文件：fclose"></a>关闭文件：fclose</h3><p>语法：<code>int  fclose (FILE * fp) ;</code> </p>
<p>返回值：如果成功关闭文件，则返回0，如果关闭文件时发生错误，则返回EOF。</p>
<h3 id="文件的顺序读写："><a href="#文件的顺序读写：" class="headerlink" title="文件的顺序读写："></a>文件的顺序读写：</h3><h4 id="按照字符读写文件：fputc-fgetc"><a href="#按照字符读写文件：fputc-fgetc" class="headerlink" title="按照字符读写文件：fputc,fgetc"></a>按照字符读写文件：fputc,fgetc</h4><ol>
<li>读文件：fgetc（从给定输入流中读取下一个字符）</li>
</ol>
<ul>
<li><p>语法：<code>int fgetc(FILE* stream) ;</code></p>
</li>
<li><p>返回值：成功时返回将读取到的字符转化为int类型的字符，失败时返回EOF</p>
</li>
</ul>
<p>注意：fgetc常与feof配合使用，如下面这个例子实现了把fp1的内容拷贝到fp2中去，并在读取完成后时退出循环。</p>
<p>补充：feof 的功能时检查本字符的下一个字符是否已经抵达给定文件流的结尾，如果抵达则返回非零，如果未抵达则返回0</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line"><span class="type">char</span> ch = fgetc(fp1);</span><br><span class="line"><span class="keyword">if</span>(feof(fp1))&#123;</span><br><span class="line"> <span class="keyword">break</span>;</span><br><span class="line">&#125;</span><br><span class="line">fputc(ch,fp2);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>写文件：fputc(将一个字符写到文件中)</li>
</ol>
<ul>
<li><p>语法：<code>int fputc(int ch,FILE*fp)</code></p>
</li>
<li><p>功能：将char转化为unsigned char后写入fp文件中</p>
</li>
<li><p>参数：ch:需要写入的文件的字符</p>
<p>​           stream:文件指针（所以在此之前需要用fopen获得文件的指针）</p>
</li>
<li><p>返回值：成功：返回成功写入的字符</p>
<p>​              失败：返回EOF</p>
</li>
</ul>
<p>示例：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">()</span>&#123;</span><br><span class="line"><span class="comment">//打开文件</span></span><br><span class="line">FILE*fp = fopen(<span class="string">&quot;./a.txt&quot;</span>,<span class="string">&quot;w&quot;</span>);</span><br><span class="line"><span class="type">char</span> s[]=<span class="string">&quot;abcd&quot;</span>;</span><br><span class="line"><span class="type">int</span> i=<span class="number">0</span>;</span><br><span class="line"><span class="comment">//将字符串写入文件</span></span><br><span class="line"><span class="keyword">while</span>(s[i])&#123;</span><br><span class="line">  fputc(s[i],fp);<span class="comment">//后续都会按照次序依次“流入”文件流中，因为文件指针会默认后移，而不是每次循环的时候都从头</span></span><br><span class="line">  i++;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//关闭文件</span></span><br><span class="line">fclose(fp);</span><br><span class="line"><span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="按照行读写文件：fgets-fputs"><a href="#按照行读写文件：fgets-fputs" class="headerlink" title="按照行读写文件：fgets,fputs"></a>按照行读写文件：fgets,fputs</h4><ol>
<li><p>读文件：fgets(只能操作字符串，泵操作二进制文件)</p>
<ul>
<li><p>语法：<code>char*fgets(char *str,int size,FILE *stream)</code></p>
</li>
<li><p>参数：str:指向字符串的指针，size:你指定的最大读取字符串的长度（会自动加”&#x2F;0”所以只能读n-1个）stream：文件指针</p>
</li>
<li><p>功能：从stream指向的文件中读取字符，保存到str所志昂的内存空间中，直到出现①换行符②读到文件结尾③读了size-1个字符为止</p>
</li>
<li><p>返回值：成功：成功读取的字符串首元素的地址</p>
<p>​              失败：读到文件结尾或者出错：NULL(空指针)</p>
</li>
</ul>
<p>示例：</p>
<p>a.txt</p>
<p>‘a’ ‘b’ ‘\n’</p>
<p>‘c’ ‘\0’  ‘d’ ‘e’  ‘f’ ‘g’ ‘j’ ‘\n’</p>
<p>‘\0’ ‘x’ ‘y’  ‘\n’</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">char</span> buf[<span class="number">5</span>];</span><br><span class="line">FILE*fp = fopen(<span class="string">&quot;a.txt&quot;</span>,<span class="string">&quot;r&quot;</span>);</span><br><span class="line">fgets(buf,<span class="number">5</span>,fp);</span><br></pre></td></tr></table></figure>

<p>一共需要读4次，每次存放到buf中的内容如下：<br>第一次： a b ‘\n’ ‘\0’ [遇到换行符就终止，并且加上’\0’]</p>
<p>第二次：c ‘\0’ d e ‘\0’ [size&#x3D;5，所以最多只能读取4个字符]</p>
<p>第三次：f g j ‘\n’ ‘\0’ [遇到换行符]</p>
<p>第四次：’\0’ x y ‘\n’ ‘\0’</p>
</li>
<li><p>写文件：fputs</p>
<ul>
<li><p>语法：int fputs(const char *str,FILE *stream)</p>
</li>
<li><p>功能：将str所指向的字符串写入到stream所指向的文件中，且字符串中的结束符’\0’不会写入文件</p>
</li>
<li><p>返回值：成功：非负值</p>
<p>​              失败：EOF  ，遇到’\0’就结束了，所以中间有’\0’就终止读入了</p>
</li>
</ul>
</li>
</ol>
<h3 id="文件路径"><a href="#文件路径" class="headerlink" title="文件路径"></a>文件路径</h3><ol>
<li><p>绝对路径：目标文件在磁盘上的真实路径，比如：D:\A\bupt\高数</p>
</li>
<li><p>相对路径：</p>
<p>引用上级文件： ..&#x2F;1.jpg</p>
<p>引用同级文件：1.jpg</p>
<p>引用下级文件：picture&#x2F;1.jpg</p>
<p>引用上上级文件：..&#x2F;..&#x2F;1.jpg</p>
</li>
</ol>
<h3 id="简易文件压缩"><a href="#简易文件压缩" class="headerlink" title="简易文件压缩"></a>简易文件压缩</h3><p>前置知识：</p>
<ul>
<li><p><code>int main(int argc,char* argv[ ])</code></p>
<p>argc（argument counter）：是命令行总的参数个数</p>
<p>argv[]（argument value）：指针数组，用来存放指向命令行参数（字符串）的指针，每个元素指向一个参数。</p>
<p>argv[0] : 可编译程序（.exe）的在电脑中绝对路径</p>
<p>argv[argc]：NULL</p>
</li>
<li><p><code>int fprintf( FILE *stream, const char *format, ... );</code></p>
<p>类似与printf，format可以是%s，%d等等</p>
<p>示例：</p>
<p>a.txt 内容：小熊</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">()</span> &#123;</span><br><span class="line">	FILE*fp=fopen(<span class="string">&quot;./a.txt&quot;</span>,<span class="string">&quot;a&quot;</span>);</span><br><span class="line">	<span class="built_in">fprintf</span>(fp,<span class="string">&quot;%s %s %s&quot;</span>,<span class="string">&quot;喜欢春天&quot;</span>,<span class="string">&quot; 我也喜欢春天&quot;</span>,<span class="string">&quot; 你呢&quot;</span>);</span><br><span class="line">	fclose(fp);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行后：</p>
<p>a.txt内容：小熊喜欢春天 我也喜欢春天 你呢</p>
<p>所以<code>fprintf(stderr, &quot;Usage: %s filename\n&quot;, argv[0]);</code>的意思是将错误信息写进stderr这个标准错误文件中。</p>
</li>
<li><p>exit（）</p>
<p>exit(0)代表程序正常退出，其余都表示异常终止，可以通过返回的具体的数值来判断出错的根源在哪里</p>
</li>
<li><p>“&lt;” 输入重定向 </p>
<p>“&gt;”输出重定向</p>
</li>
</ul>
<p>代码详解：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span>    <span class="comment">// for exit()</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;string.h&gt;</span>    <span class="comment">// for strcpy(), strcat()</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> LEN 40</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">    FILE  *in, *out;   </span><br><span class="line">    <span class="type">int</span> ch;</span><br><span class="line">    <span class="type">char</span> name[LEN];    </span><br><span class="line">    <span class="type">int</span> count = <span class="number">0</span>;</span><br><span class="line"><span class="comment">// 检查命令行参数 </span></span><br><span class="line"><span class="comment">//如果命令行的参数等于1，则不用压缩，因为本程序是将每三个字符压缩成1个字符，所以在标准错误输出中弹出错误提示信息</span></span><br><span class="line">    <span class="keyword">if</span> (argc &lt; <span class="number">2</span>)</span><br><span class="line">    &#123;</span><br><span class="line">         <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">&quot;Usage: %s filename\n&quot;</span>, argv[<span class="number">0</span>]);</span><br><span class="line">         <span class="built_in">exit</span>(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">//argv[1]:作为输入流参数的文件的名字，如果文件打开失败，则在标准输出中弹出无法打开文件</span></span><br><span class="line">    <span class="keyword">if</span> ((in = fopen(argv[<span class="number">1</span>], <span class="string">&quot;r&quot;</span>)) == <span class="literal">NULL</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">&quot;I couldn&#x27;t open the file \&quot;%s\&quot;\n&quot;</span>,</span><br><span class="line">                argv[<span class="number">1</span>]);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//将输入的文件名字字符串拷贝到name字符数组中</span></span><br><span class="line">    <span class="built_in">strcpy</span>(name,argv[<span class="number">1</span>]); </span><br><span class="line">    <span class="comment">//将name字符数组后面追加上后缀，即.red</span></span><br><span class="line">    <span class="built_in">strcat</span>(name,<span class="string">&quot;.red&quot;</span>);    </span><br><span class="line">    <span class="comment">//打开name这个文件夹，(如果你将a.txt作为输入流，那么这时候name字符串就是a.txt.red，打开的就是待压缩的文件),因为是以只写的方式打开，且之前并没有这个文件，所以会新建这个文件。</span></span><br><span class="line">    <span class="comment">//下面这个if是判断如果打开文件失败，则在标准错误输出中输出“不能创建output文件”，并exit(3)</span></span><br><span class="line">    <span class="keyword">if</span> ((out = fopen(name, <span class="string">&quot;w&quot;</span>)) == <span class="literal">NULL</span>)</span><br><span class="line">    &#123;                       <span class="comment">// open file for writing</span></span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>,<span class="string">&quot;Can&#x27;t create output file.\n&quot;</span>);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">3</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line"><span class="comment">//压缩文件，用getc(in)) != EOF判断是否读到了文件末尾，每隔三个字符将其中的第一个字符写入out所指向的文件中（也就是a.txt.red)</span></span><br><span class="line">    <span class="keyword">while</span> ((ch = getc(in)) != EOF)</span><br><span class="line">        <span class="keyword">if</span> (count++ % <span class="number">3</span> == <span class="number">0</span>)</span><br><span class="line">            putc(ch, out);  </span><br><span class="line"></span><br><span class="line"><span class="comment">//关闭文件</span></span><br><span class="line">    <span class="keyword">if</span> (fclose(in) != <span class="number">0</span> || fclose(out) != <span class="number">0</span>)</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>,<span class="string">&quot;Error in closing files\n&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>

<h4 id="方法："><a href="#方法：" class="headerlink" title="方法："></a>方法：</h4><p>在程序同一个目录下创建一个a.txt，然后再命令行里输入<img src="/../img/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/image-20220402111008546.png" alt="image-20220402111008546"></p>
<p>即程序名+空格+待压缩文件</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/C%E8%AF%AD%E8%A8%80/" rel="tag"># C语言</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2022/03/30/%E7%A6%BB%E6%95%A3%E6%95%B0%E5%AD%A6%E3%81%AE%E7%AC%94%E8%AE%B0/" rel="prev" title="离散数学の笔记">
      <i class="fa fa-chevron-left"></i> 离散数学の笔记
    </a></div>
      <div class="post-nav-item">
    <a href="/2022/04/02/CSS/" rel="next" title="CSS自学笔记">
      CSS自学笔记 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E5%88%86%E7%B1%BB"><span class="nav-number">1.</span> <span class="nav-text">文件分类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AE%BE%E5%A4%87%E6%96%87%E4%BB%B6"><span class="nav-number">2.</span> <span class="nav-text">设备文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E7%9A%84%E9%87%8D%E5%AE%9A%E5%90%91"><span class="nav-number">3.</span> <span class="nav-text">文件的重定向</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E8%AE%BF%E9%97%AE%E6%96%B9%E5%BC%8F"><span class="nav-number">4.</span> <span class="nav-text">文件访问方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%89%93%E5%BC%80%E6%96%87%E4%BB%B6%EF%BC%9Afopen"><span class="nav-number">5.</span> <span class="nav-text">打开文件：fopen</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%B3%E9%97%AD%E6%96%87%E4%BB%B6%EF%BC%9Afclose"><span class="nav-number">6.</span> <span class="nav-text">关闭文件：fclose</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E7%9A%84%E9%A1%BA%E5%BA%8F%E8%AF%BB%E5%86%99%EF%BC%9A"><span class="nav-number">7.</span> <span class="nav-text">文件的顺序读写：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%8C%89%E7%85%A7%E5%AD%97%E7%AC%A6%E8%AF%BB%E5%86%99%E6%96%87%E4%BB%B6%EF%BC%9Afputc-fgetc"><span class="nav-number">7.1.</span> <span class="nav-text">按照字符读写文件：fputc,fgetc</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%8C%89%E7%85%A7%E8%A1%8C%E8%AF%BB%E5%86%99%E6%96%87%E4%BB%B6%EF%BC%9Afgets-fputs"><span class="nav-number">7.2.</span> <span class="nav-text">按照行读写文件：fgets,fputs</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84"><span class="nav-number">8.</span> <span class="nav-text">文件路径</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%AE%80%E6%98%93%E6%96%87%E4%BB%B6%E5%8E%8B%E7%BC%A9"><span class="nav-number">9.</span> <span class="nav-text">简易文件压缩</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%B9%E6%B3%95%EF%BC%9A"><span class="nav-number">9.1.</span> <span class="nav-text">方法：</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="芷若"
      src="/images/touxiang.jpg">
  <p class="site-author-name" itemprop="name">芷若</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">19</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/zhiruo" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;zhiruo" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">陕ICP备2022001874号 </a>
      <img src="http://www.beian.gov.cn/portal/download" style="display: inline-block;">
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="芷若"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">芷若</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">105k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">1:35</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="//cdn.jsdelivr.net/npm/algoliasearch@4/dist/algoliasearch-lite.umd.js"></script>
<script src="//cdn.jsdelivr.net/npm/instantsearch.js@4/dist/instantsearch.production.min.js"></script>
<script src="/js/algolia-search.js"></script>














  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/assets/koharu.model.json"},"display":{"position":"right","width":145,"height":315},"mobile":{"show":true,"scale":0.5},"react":{"opacityDefault":0.7,"opacityOnHover":0.8},"log":false});</script></body>
</html>
